<template>
  <a-tabs
    :activeKey="activeKey"
    @change="handleChange"
    @edit="handleEdit"
    :type="tabsData.length > 1 ? 'editable-card' : 'card'"
    hideAdd
    :class="$style.tabs"
  >
    <a-tab-pane v-for="pane in tabsData" :key="pane.path" :tab="pane.pageName || pane.path" closable></a-tab-pane>
  </a-tabs>
</template>

<script lang="ts">
  import { defineComponent, watch } from 'vue'
  import { useCacheViews, MenuList } from  './cache'

  export default defineComponent({
    setup(props, context) {
      const { includeNames, tabsData, removeCacheView } =  useCacheViews(props.menu)
      const  handleEdit = (targetKey: string, action: string) => {
        if (action === 'remove') {
          removeCacheView(targetKey)
        }
      }
      watch(() => tabsData.value, () => {
        context.emit('change', includeNames)
      }, { immediate: true })

      return {
        includeNames, 
        tabsData,
        handleEdit
      }
    },
    props: {
      menu: {
        type: Array as () => MenuList,
        default: () => []
      }
    },
    emits: ['change'],
    computed: {
      activeKey(): string {
        const current: any = this.tabsData.find((item: any) => {
          return item.active
        })
        return current ? current.path : ''
      }
    },
    methods: {
      handleChange(path: any) {
        this.$router.push(path)
      }
    }
  })
</script>

<style lang="scss" module>
  .tabs {
    :global(.ant-tabs-bar) {
      margin-bottom: 0;
    }
  }
</style>